import {showInfo, getAllResources} from "./init";
import {BrowserWindow, ipcMain, net } from "electron";
import {WebSocket} from "ws";
import {app} from "electron";
import { HttpsProxyAgent } from 'https-proxy-agent';


const heartbeatInterval = 5000; // 心跳检测间隔

const state = {
    signalingServer: '',
    signalingState: 'disconnected',
    sources: [],
    userId: "",
};

//用于websocket  http://10.22.0.29:8080
let ws,
    heartbeatTimer;


// 创建通过代理的 WebSocket
export async function createWebSocketWithProxy(url) {
    let options = {
        handshakeTimeout: 10000, // 10秒超时
        perMessageDeflate: false
    };
    let str = url.replaceAll('http:', '').replaceAll('https:', '').replaceAll('//', ''),
        proxy = global.appStore.get("proxy_url");
    if (proxy && str.substring(0, 5) !== 'local' && str.substring(0, 3) !== '10.' && str.substring(0, 3) !== '11.' && str.substring(0, 4) !== '127.' && str.substring(0, 4) !== '192.' && str.substring(0, 4) !== '172.'){
        console.log("------------createWebSocketWithProxy------------")
        options.agent = new HttpsProxyAgent(proxy);  //http://10.22.0.29:8080
    }

    return new WebSocket(url, options)
}


// 信令服务器连接
const connectSignaling = async () => {
    try {
        let myClientId = global.appStore.get("user_id");
        if (!myClientId) return

        console.log('server_url_is:', state.signalingServer)
        ws = await createWebSocketWithProxy(state.signalingServer);

        ws.onopen = () => {
            state.signalingState = 'connected';
            logMessage('connectSignaling success');
            sendSignalingMessage({
                type: 'status',
                data: {
                    room: "",
                    user_id: myClientId,
                    control_by: "",
                    control_flag: true,
                    preview_img: state.sources[0].thumbnail,
                    screens: state.sources,
                },
                from: myClientId,
                to: "",
            });
        };

        ws.onmessage = (event) => {
            if (event.data === "pong") return; //忽略心跳消息
            BrowserWindow.getAllWindows().forEach(v => {
                v.webContents.send('signaling-message', JSON.parse(event.data));
            })
        };

        ws.onclose = () => {
            state.signalingState = 'disconnected';
            logMessage('connectSignaling disconnect');
        };

        ws.onerror = (error) => {
            logMessage(`[${state.signalingServer}] connectSignalingErr: ${error.error.code}`);
        };

        return ws;
    } catch (error) {
        logMessage(`connectSignaling connectFail: ${error.message}`);
    }
};

const disconnectSignaling = () => {
    if (ws) {
        ws.close();
        ws = null;
    }
};

// 发送信令消息
const sendSignalingMessage = (msg) => {
    let message = typeof msg === 'string' ? JSON.parse(msg) : msg;
    message.from = state.userId;
    if (ws && ws.readyState === WebSocket.OPEN) {
        // ws.send(JSON.stringify(message));
        ws.send(JSON.stringify(message));
        logMessage(`sendSignalingMessage: ${message.type}`);
    }
};


// 日志记录
const logMessage = (message) => {
    const timestamp = new Date().toLocaleTimeString();
    console.log(timestamp, message)
    BrowserWindow.getAllWindows().forEach(v => {
        v.webContents.send('signaling-log-message', message);
    })
};

// 心跳检测状态
function startHeartbeat() {
    heartbeatTimer = setInterval(() => {
        if (!ws || ![WebSocket.OPEN, WebSocket.CONNECTING].includes(ws.readyState)) { // 如果断开连接，发起重连
            logMessage("sendSignalingMessage reconnect", ws);
            connectSignaling();
        } else if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send("ping"); // 心跳保持
        }
    }, heartbeatInterval);
}


export async function setWs(){
    state.userId = global.appStore.get("user_id");
    state.signalingServer = `ws://${global.appStore.get("server_url")}/ws?client=${state.userId}`;
    state.sources = await getAllResources({
        types: ['screen'],
        thumbnailSize: {width: 320, height: 180}
    });
    let client = global.appStore.get("user_id");
    if (!client) {
        showInfo("用户ID未设置，请设置完后重启APP");
        return false;
    }
    connectSignaling();
    startHeartbeat();

    ipcMain.handle('send-signaling-message', (event, message) => {
        sendSignalingMessage(message);
    });


    ipcMain.handle('get-signaling-state', (event) => {
        return state;
    });

}

//关闭app时关闭websocket连接
app.on('before-quit', () => {
    if (ws) {
        ws.close();
    }
});


